﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using sixgod.Base.Controllers;
using sixgod.Common.Exception;
using sixgod.Dtos.WorkFlow;
using sixgod.Dtos.WorkFlow.Query;
using sixgod.Service.WorkFlow;

namespace sixgod.Module.WorkFlow.Controllers
{
    [Route("[Controller]")]
    public class WorkFlowController: BaseController
    {
        private readonly IWorkFlowService _workFlowService;
        private readonly IMapper _mapper;

        public WorkFlowController(IWorkFlowService workFlowService, IMapper mapper)
        {
            _workFlowService = workFlowService;
            _mapper = mapper;
        }
        
        [HttpGet("page")]
        public async Task<IActionResult> GetPageList([FromQuery]WorkFlowQuery query)
        {
            var result = await _workFlowService.GetPageList(query);
            return Success(result);
        }

        [HttpGet("flowInfo/{id}")]
        public async Task<IActionResult> GetWorkFlowInfo(string id)
        {
            var data = await _workFlowService.GetWorkFlowDetailDto(id);
            return Success(data);
        }

        [HttpGet("formItems/{id}")]
        public async Task<IActionResult> GetFlowFormItems(string id)
        {
            var list = await _workFlowService.GetFormItems(id);
            var dto = _mapper.Map<List<FormItemDto>>(list);
            return Success(dto);
        }

        [HttpPut("restart")]
        public async Task<IActionResult> ReStartWorkFlow([FromBody]StartWorkFlowInDto data)
        {
            await _workFlowService.ReStartWorkFlow(data);
            return Success("操作成功");
        }

        /// <summary>
        /// 流程审核
        /// </summary>
        /// <returns></returns>
        [HttpPut("audit")]
        public async Task<IActionResult> AuditFlow([FromBody]FlowExecuteInDto data)
        {
            try
            {
                await _workFlowService.AuditFlow(data);
                return Success("操作成功");
            }
            catch (Exception e)
            {
                return Fail(e.Message);
            }
        }

        [HttpPost]
        public async Task<IActionResult> StartWorkFlow([FromBody]StartWorkFlowInDto data)
        {
            try
            {
                await _workFlowService.StartWorkFlow(data);
                return Success("操作成功");
            }
            catch (Exception e)
            {
                return e is WorkFlowException ? Fail(e.Message) : Fail("系统错误："+e.Message);
            }
        }
    } 
}
